import pygame
import random
import sys

# 初始化pygame
pygame.init()

# 游戏设置
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 400
FPS = 60
GRAVITY = 0.8
JUMP_STRENGTH = -15
GROUND_HEIGHT = 50

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (128, 128, 128)
DARK_GRAY = (64, 64, 64)
GREEN = (34, 139, 34)

# 创建游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("恐龙跳跃 - Dino Jump")
clock = pygame.time.Clock()

class Dinosaur:
    def __init__(self):
        self.width = 40
        self.height = 60
        self.x = 100
        self.y = SCREEN_HEIGHT - GROUND_HEIGHT - self.height
        self.vel_y = 0
        self.jumping = False
        self.ducking = False
        self.run_timer = 0

    def jump(self):
        if not self.jumping:
            self.vel_y = JUMP_STRENGTH
            self.jumping = True

    def duck(self):
        if not self.jumping:
            self.ducking = True
            self.height = 30
            self.y = SCREEN_HEIGHT - GROUND_HEIGHT - self.height

    def stand_up(self):
        self.ducking = False
        self.height = 60
        self.y = SCREEN_HEIGHT - GROUND_HEIGHT - self.height

    def update(self):
        # 应用重力
        self.vel_y += GRAVITY
        self.y += self.vel_y

        # 地面碰撞检测
        if self.y >= SCREEN_HEIGHT - GROUND_HEIGHT - self.height:
            self.y = SCREEN_HEIGHT - GROUND_HEIGHT - self.height
            self.vel_y = 0
            self.jumping = False

        # 更新跑步动画
        self.run_timer += 1

    def draw(self):
        # 绘制简化的恐龙形状
        # 身体
        body_color = DARK_GRAY
        pygame.draw.rect(screen, body_color, (self.x, self.y + 20, self.width - 10, self.height - 20))

        # 头部
        pygame.draw.rect(screen, body_color, (self.x + self.width - 15, self.y, 15, 20))

        # 腿部动画
        leg_offset = (self.run_timer // 5) % 2 * 5
        pygame.draw.rect(screen, body_color, (self.x + 5, self.y + self.height - 15, 8, 15 - leg_offset))
        pygame.draw.rect(screen, body_color, (self.x + 20, self.y + self.height - 15, 8, 15 - (5 - leg_offset)))

        # 尾巴
        pygame.draw.polygon(screen, body_color, [
            (self.x, self.y + 30),
            (self.x - 15, self.y + 35),
            (self.x - 10, self.y + 40)
        ])

        # 眼睛
        pygame.draw.circle(screen, WHITE, (self.x + self.width - 8, self.y + 8), 3)
        pygame.draw.circle(screen, BLACK, (self.x + self.width - 7, self.y + 8), 2)

    def get_rect(self):
        return pygame.Rect(self.x, self.y, self.width, self.height)

class Cactus:
    def __init__(self, x):
        self.x = x
        self.width = random.randint(20, 40)
        self.height = random.randint(40, 60)
        self.y = SCREEN_HEIGHT - GROUND_HEIGHT - self.height
        self.speed = 8

    def update(self):
        self.x -= self.speed

    def draw(self):
        # 绘制仙人掌
        color = GREEN
        # 主干
        pygame.draw.rect(screen, color, (self.x + self.width//2 - 5, self.y, 10, self.height))
        # 左臂
        pygame.draw.rect(screen, color, (self.x, self.y + 15, 15, 8))
        # 右臂
        pygame.draw.rect(screen, color, (self.x + self.width - 15, self.y + 20, 15, 8))

    def get_rect(self):
        return pygame.Rect(self.x, self.y, self.width, self.height)

    def is_off_screen(self):
        return self.x < -self.width

class Cloud:
    def __init__(self):
        self.x = SCREEN_WIDTH + random.randint(100, 300)
        self.y = random.randint(50, 150)
        self.width = random.randint(60, 100)
        self.height = 30
        self.speed = random.uniform(1, 2)

    def update(self):
        self.x -= self.speed
        if self.x < -self.width:
            self.x = SCREEN_WIDTH + random.randint(100, 300)
            self.y = random.randint(50, 150)

    def draw(self):
        # 绘制简单的云朵
        pygame.draw.ellipse(screen, WHITE, (self.x, self.y, self.width, self.height))
        pygame.draw.ellipse(screen, WHITE, (self.x - 20, self.y + 5, 40, 20))
        pygame.draw.ellipse(screen, WHITE, (self.x + self.width - 20, self.y + 5, 40, 20))

class Game:
    def __init__(self):
        self.dinosaur = Dinosaur()
        self.cacti = []
        self.clouds = [Cloud() for _ in range(3)]
        self.score = 0
        self.high_score = 0
        self.game_over = False
        self.game_started = False
        self.spawn_timer = 0
        self.font_large = pygame.font.Font(None, 48)
        self.font_medium = pygame.font.Font(None, 36)
        self.font_small = pygame.font.Font(None, 24)

    def spawn_cactus(self):
        self.spawn_timer += 1
        if self.spawn_timer > random.randint(60, 120):  # 随机间隔生成仙人掌
            self.cacti.append(Cactus(SCREEN_WIDTH))
            self.spawn_timer = 0

    def update(self):
        if not self.game_started or self.game_over:
            return

        # 更新恐龙
        self.dinosaur.update()

        # 更新仙人掌
        for cactus in self.cacti[:]:
            cactus.update()
            if cactus.is_off_screen():
                self.cacti.remove(cactus)
                self.score += 10

        # 更新云朵
        for cloud in self.clouds:
            cloud.update()

        # 生成新的仙人掌
        self.spawn_cactus()

        # 碰撞检测
        dino_rect = self.dinosaur.get_rect()
        for cactus in self.cacti:
            if dino_rect.colliderect(cactus.get_rect()):
                self.game_over = True
                if self.score > self.high_score:
                    self.high_score = self.score

    def draw_ground(self):
        # 绘制地面
        pygame.draw.rect(screen, DARK_GRAY, (0, SCREEN_HEIGHT - GROUND_HEIGHT, SCREEN_WIDTH, GROUND_HEIGHT))
        # 绘制地面线条
        pygame.draw.line(screen, GRAY, (0, SCREEN_HEIGHT - GROUND_HEIGHT),
                        (SCREEN_WIDTH, SCREEN_HEIGHT - GROUND_HEIGHT), 2)

        # 绘制地面纹理
        for i in range(0, SCREEN_WIDTH, 40):
            pygame.draw.line(screen, GRAY, (i, SCREEN_HEIGHT - GROUND_HEIGHT + 10),
                           (i + 20, SCREEN_HEIGHT - GROUND_HEIGHT + 10), 1)

    def draw_start_screen(self):
        screen.fill(WHITE)

        # 绘制标题
        title_text = self.font_large.render("DINO JUMP", True, BLACK)
        title_rect = title_text.get_rect(center=(SCREEN_WIDTH // 2, 100))
        screen.blit(title_text, title_rect)

        # 绘制说明
        instructions = [
            "Press SPACE or UP to Jump",
            "Press DOWN to Duck",
            "Avoid the cacti!",
            "",
            "Press SPACE to Start"
        ]

        y = 200
        for instruction in instructions:
            text = self.font_small.render(instruction, True, BLACK)
            text_rect = text.get_rect(center=(SCREEN_WIDTH // 2, y))
            screen.blit(text, text_rect)
            y += 30

    def draw_game_over_screen(self):
        # 半透明覆盖层
        overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
        overlay.set_alpha(180)
        overlay.fill(WHITE)
        screen.blit(overlay, (0, 0))

        # 游戏结束文字
        game_over_text = self.font_large.render("GAME OVER", True, BLACK)
        game_over_rect = game_over_text.get_rect(center=(SCREEN_WIDTH // 2, 120))
        screen.blit(game_over_text, game_over_rect)

        # 分数显示
        score_text = self.font_medium.render(f"Score: {self.score}", True, BLACK)
        score_rect = score_text.get_rect(center=(SCREEN_WIDTH // 2, 180))
        screen.blit(score_text, score_rect)

        high_score_text = self.font_medium.render(f"High Score: {self.high_score}", True, BLACK)
        high_score_rect = high_score_text.get_rect(center=(SCREEN_WIDTH // 2, 220))
        screen.blit(high_score_text, high_score_rect)

        # 重新开始提示
        restart_text = self.font_small.render("Press SPACE to Restart", True, BLACK)
        restart_rect = restart_text.get_rect(center=(SCREEN_WIDTH // 2, 280))
        screen.blit(restart_text, restart_rect)

        quit_text = self.font_small.render("Press ESC to Quit", True, BLACK)
        quit_rect = quit_text.get_rect(center=(SCREEN_WIDTH // 2, 320))
        screen.blit(quit_text, quit_rect)

    def draw(self):
        # 清屏
        screen.fill(WHITE)

        # 绘制云朵
        for cloud in self.clouds:
            cloud.draw()

        # 绘制地面
        self.draw_ground()

        if not self.game_started:
            self.draw_start_screen()
        else:
            # 绘制仙人掌
            for cactus in self.cacti:
                cactus.draw()

            # 绘制恐龙
            self.dinosaur.draw()

            # 显示分数
            score_text = self.font_medium.render(f"Score: {self.score}", True, BLACK)
            screen.blit(score_text, (10, 10))

            high_score_text = self.font_small.render(f"High: {self.high_score}", True, BLACK)
            screen.blit(high_score_text, (10, 50))

            if self.game_over:
                self.draw_game_over_screen()

    def reset_game(self):
        self.dinosaur = Dinosaur()
        self.cacti = []
        self.score = 0
        self.game_over = False
        self.spawn_timer = 0

    def handle_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return False

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    return False

                if not self.game_started:
                    if event.key == pygame.K_SPACE:
                        self.game_started = True
                        self.reset_game()

                elif self.game_over:
                    if event.key == pygame.K_SPACE:
                        self.reset_game()

                else:
                    if event.key == pygame.K_SPACE or event.key == pygame.K_UP:
                        self.dinosaur.jump()
                    elif event.key == pygame.K_DOWN:
                        self.dinosaur.duck()

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_DOWN:
                    self.dinosaur.stand_up()

        # 持续按键检测（用于跳跃）
        if self.game_started and not self.game_over:
            keys = pygame.key.get_pressed()
            if keys[pygame.K_SPACE] or keys[pygame.K_UP]:
                if self.dinosaur.jumping and self.dinosaur.vel_y < -5:  # 允许长按跳得更高
                    self.dinosaur.vel_y -= 0.5
            if keys[pygame.K_DOWN]:
                self.dinosaur.duck()

        return True

    def run(self):
        running = True
        while running:
            running = self.handle_events()
            self.update()
            self.draw()
            pygame.display.flip()
            clock.tick(FPS)

        pygame.quit()
        sys.exit()

# 运行游戏
if __name__ == "__main__":
    game = Game()
    game.run()